<?php

namespace app\api\controller;

use think\facade\Lang;
use think\facade\Db;

/**
 * ============================================================================
 * DSKMS多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家商品控制器
 */
class Sellergoods extends MobileSeller {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellergoodsadd.lang.php');
    }

    /**
     * @api {POST} api/Sellergoods/goods_list 出售中的商品列表
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} keyword 关键词
     * @apiParam {String} goods_type 商品类型 lockup违规的商品 offline仓库的商品 waitverify等待审核的商品
     * @apiParam {Int} search_type 0商品名 1货号 2商品公共ID
     * @apiParam {String} page 页码
     * @apiParam {String} pagesize 每页显示数量
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.goods_list  商品列表
     * @apiSuccess {String} result.goods_list.goods_addtime  添加时间
     * @apiSuccess {String} result.goods_list.goods_commonid  商品公共ID
     * @apiSuccess {String} result.goods_list.goods_image  商品图片
     * @apiSuccess {String} result.goods_list.goods_lock  商品锁定 0未锁，1已锁
     * @apiSuccess {String} result.goods_list.goods_name  商品名称
     * @apiSuccess {String} result.goods_list.goods_price  商品价格
     * @apiSuccess {String} result.goods_list.goods_state  商品状态 0:下架 1:正常 10:违规（禁售）
     * @apiSuccess {String} result.goods_list.goods_storage_sum  商品库存
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function goods_list() {
        $keyword = input('post.keyword');
        $goods_type = input('post.goods_type');
        $search_type = input('post.search_type');

        $goods_model = model('goods');

        $condition = array();
        $condition[] = array('store_id', '=', $this->store_info['store_id']);
        if (trim($keyword) != '') {
            switch ($search_type) {
                case 0:
                    $condition[] = array('goods_name', 'like', '%' . trim($keyword) . '%');
                    break;
                case 1:
                    $condition[] = array('goods_serial', 'like', '%' . trim($keyword) . '%');
                    break;
                case 2:
                    $condition[] = array('goods_commonid', '=', intval($keyword));
                    break;
            }
        }

        $fields = 'gc_id,goods_id,goods_name,goods_price,goods_addtime,goods_image,goods_state,goods_lock,goods_salenum';
        switch ($goods_type) {
            // 违规的商品
            case 'lockup':
                $goods_list = $goods_model->getGoodsLockUpList($condition, $fields, $this->pagesize);
                break;
            //仓库的商品
            case 'offline':
                $goods_list = $goods_model->getGoodsOfflineList($condition, $fields, $this->pagesize);
                break;
            //等待审核的商品
            case 'waitverify':
                $goods_list = $goods_model->getGoodsWaitVerifyList($condition);
                break;
            default:
                $goods_list = $goods_model->getGoodsOnlineList($condition, $fields, $this->pagesize);
                break;
        }


        // 整理输出的数据格式
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['goods_addtime'] = date('Y-m-d', $goods_list[$key]['goods_addtime']);
            $goods_list[$key]['goods_image'] = goods_cthumb($goods_list[$key]['goods_image']);
        }

        $result = array_merge(array('goods_list' => $goods_list), mobile_page($goods_model->page_info));
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/goods_show 商品上架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} goodsid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_show() {
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001, '机构正在审核中或已经关闭，不能上架商品');
        }

        $goodsid = input('param.goods_id');
        if (!preg_match('/^[\d,]+$/i', $goodsid)) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodsid_array = explode(',', $goodsid);
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001, lang('store_goods_index_goods_show_fail'));
        }
        $condition = array();
        $condition[] = array('goods_id', 'in', $goodsid_array);
        $condition[] = array('store_id', '=', $this->store_info['store_id']);
        $return = model('goods')->editProducesOnline($condition);
        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('商品上架，平台货号：' . $goodsid);
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_show_fail'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品下架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} goodsid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_unshow() {
        //参考PC端代码
        $common_id = $this->checkRequestCommonId(input('param.goods_id'));
        $goodsid_array = explode(',', $common_id);
        $goods_model = model('goods');
        $where = array();
        $where[] = array('goods_id', 'in', $goodsid_array);
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        $return = model('goods')->editProducesOffline($where);
        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('商品下架，平台货号：' . $common_id);
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_unshow_fail'));
        }
    }

    /**
     * 验证goodsid
     */
    private function checkRequestCommonId($common_ids) {
        if (!preg_match('/^[\d,]+$/i', $common_ids)) {
            ds_json_encode(10001, lang('para_error'));
        }
        return $common_ids;
    }

    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品删除
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} goodsid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function drop_goods() {
        $goodsid = input('param.goods_id');
        $common_id = $this->checkRequestCommonId($goodsid);
        $goodsid_array = explode(',', $common_id);

        $goods_model = model('goods');
        $where = array();
        $where[] = array('goods_id', 'in', $goodsid_array);
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        $return = $goods_model->delGoodsNoLock($where);

        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('删除商品，平台货号：' . $common_id);
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_del_fail'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/get_goodsclass_list 获取新增/编辑商品的公共数据
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} class_id 商品分类ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.goods_class  商品分类
     * @apiSuccess {Int} result.goods_class.gc_id  商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_1  一级商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_2  二级商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_3  三级商品分类ID
     * @apiSuccess {String} result.goods_class.gctag_name  商品分类名称
     * @apiSuccess {String} result.goods_class.gctag_value  商品分类标签
     */
    public function get_goodsclass_list() {
        $result = array();
        $class_id = intval(input('param.class_id'));

        $goods_class = model('goodsclass')->getGoodsclassLineForTag($class_id);
        $result['goods_class'] = $goods_class;

        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/edit_goods 获取商品信息
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} class_id 商品分类ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.goods  商品信息（返回字段参考goodscommon表）
     * @apiSuccess {Object[]} result.goods.mb_body  商品详情
     * @apiSuccess {String} result.goods.mb_body.type  商品详情类型（image图片text文字）
     * @apiSuccess {String} result.goods.mb_body.value  商品详情值
     * @apiSuccess {String} result.goods.mb_body.value_url  商品详情图片链接
     * @apiSuccess {String} result.goods.goods_image_url  商品图片
     */
    public function edit_goods() {
        $common_id = intval(input('param.goods_id'));
        if ($common_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $goodscommon_info = $goods_model->getGoodsInfo(array('goods_id' => $common_id));
        if (empty($goodscommon_info) || $goodscommon_info['store_id'] != $this->store_info['store_id'] || $goodscommon_info['goods_lock'] == 1) {
            ds_json_encode(10001, lang('goods_not_exist_or_lock'));
        }
        $result = array();
        if ($goodscommon_info['mobile_body'] != '') {
            $goodscommon_info['mb_body'] = unserialize($goodscommon_info['mobile_body']);
            if (is_array($goodscommon_info['mb_body'])) {
                $mobile_body = '[';
                foreach ($goodscommon_info['mb_body'] as $val) {
                    $mobile_body .= '{"type":"' . $val['type'] . '","value":"' . $val['value'] . '"},';
                }
                $mobile_body = rtrim($mobile_body, ',') . ']';
            }
            $goodscommon_info['mobile_body'] = $mobile_body;
        }
        $goodscommon_info['goods_image_url'] = goods_thumb($goodscommon_info, 240);
        $result['goods'] = $goodscommon_info;


        // 实例化店铺商品分类模型
        $store_goods_class = model('storegoodsclass')->getClassTree(array('store_id' => $this->store_info['store_id'], 'storegc_state' => '1'));

        //处理商品所属分类
        $store_goods_class_tmp = array();
        if (!empty($store_goods_class)) {
            foreach ($store_goods_class as $k => $v) {
                $store_goods_class_tmp[$v['storegc_id']] = $v;
                if (isset($v['child'])) {
                    foreach ($v['child'] as $son_k => $son_v) {
                        $store_goods_class_tmp[$son_v['storegc_id']] = $son_v;
                    }
                }
            }
        }
        $result['store_goods_class'] = $store_goods_class_tmp;
        $goodscommon_info['goods_stcids'] = trim($goodscommon_info['goods_stcids'], ',');
        $goods_stcids = empty($goodscommon_info['goods_stcids']) ? array() : explode(',', $goodscommon_info['goods_stcids']);
        $goods_stcids_tmp = $goods_stcids_new = array();
        if (!empty($goods_stcids)) {
            foreach ($goods_stcids as $k => $v) {
                if (isset($store_goods_class_tmp[$v])) {
                    $storegc_parent_id = $store_goods_class_tmp[$v]['storegc_parent_id'];
                } else {
                    $storegc_parent_id = 0;
                }
                //分类进行分组，构造为array('1'=>array(5,6,8));
                if ($storegc_parent_id > 0) {//如果为二级分类，则分组到父级分类下
                    $goods_stcids_tmp[$storegc_parent_id][] = $v;
                } elseif (empty($goods_stcids_tmp[$v])) {//如果为一级分类而且分组不存在，则建立一个空分组数组
                    $goods_stcids_tmp[$v] = array();
                }
            }
            foreach ($goods_stcids_tmp as $k => $v) {
                if (!empty($v) && count($v) > 0) {
                    $goods_stcids_new = array_merge($goods_stcids_new, $v);
                } else {
                    $goods_stcids_new[] = $k;
                }
            }
        }
        $result['store_class_goods'] = $goods_stcids_new;
        $result['if_baidu_pan'] = $this->store_info['baidu_pan_access_token'] ? 1 : 0;

        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/image_upload 上传商品图片
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {File} refund_pic 图片
     * @apiParam {String} name 文件表单名
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.path  文件名
     * @apiSuccess {String} result.url  文件链接
     */
    public function image_upload() {
        // 判断图片数量是否超限
        $album_model = model('album');
        $album_limit = $this->store_grade['storegrade_album_limit'];
        if ($album_limit > 0) {
            $album_count = $album_model->getCount(array('store_id' => $this->store_info['store_id']));

            if ($album_count >= $album_limit) {
                ds_json_encode(10001, lang('store_goods_album_climit'));
            }
        }
        $class_info = $album_model->getOne(array('store_id' => $this->store_info['store_id'], 'aclass_isdefault' => 1), 'albumclass');


        $store_id = $this->store_info['store_id'];
        /**
         * 上传图片
         */
        $time=TIMESTAMP;
        //上传文件保存路径
        $upload_path = ATTACH_GOODS . '/' . $store_id . '/' . date('Ymd',$time);
        $save_name = $this->store_info['store_id'] . '_' . date('YmdHis',$time) . rand(10000, 99999);
        $file_name = input('post.name');

        $result = upload_albumpic($upload_path, $file_name, $save_name);
        if ($result['code'] == '10000') {
            $img_path = $result['result'];
            list($width, $height, $type, $attr) = getimagesize($img_path);
            $img_path = substr(strrchr($img_path, "/"), 1);
        } else {
            //未上传图片或出错不做后面处理
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }

        // 存入相册
        $insert_array = array();
        $insert_array['apic_name'] = $img_path;
        $insert_array['apic_tag'] = '';
        $insert_array['aclass_id'] = $class_info['aclass_id'];
        $insert_array['apic_cover'] = $img_path;
        $insert_array['apic_size'] = intval($_FILES[$file_name]['size']);
        $insert_array['apic_spec'] = $width . 'x' . $height;
        $insert_array['apic_uploadtime'] = $time;
        $insert_array['store_id'] = $store_id;
        $result = model('album')->addAlbumpic($insert_array);



        // 整理为json格式
        ds_json_encode(10000, '', array('url' => goods_cthumb($img_path, 480, $this->store_info['store_id']), 'path' => $img_path));
    }

    /**
     * 三方店铺验证，商品数量，有效期
     */
    private function checkStore() {
        $goodsLimit = (int) $this->store_grade['storegrade_goods_limit'];
        if ($goodsLimit > 0) {
            // 是否到达商品数上限
            $goods_num = model('goods')->getGoodsCommonCount(array('store_id' => session('store_id')));
            if ($goods_num >= $goodsLimit) {
                ds_json_encode(10001, lang('store_goods_index_goods_limit') . $goodsLimit . lang('store_goods_index_goods_limit1'));
            }
        }
    }
    /**
     * @api {POST} api/Sellergoods/save_goods 保存商品信息
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} goods_id 商品ID
     * @apiParam {Int} class_id 商品分类ID
     * @apiParam {Object} goods 商品信息
     * @apiParam {String} goods.goods_name 商品名称
     * @apiParam {String} goods.goods_advword 商品广告
     * @apiParam {String} goods.goods_image 商品图片
     * @apiParam {Float} goods.goods_price 商品价格
     * @apiParam {String} goods.goods_serial 商品货号
     * @apiParam {Int} goods.goods_commend 商品推荐（0否1是）
     * @apiParam {Int} goods.goods_state 商品状态（0下架1上架）
     * @apiParam {Int} goods.goods_vat 是否开增值税发票（0否1是）
     * @apiParam {Int[]} sgcate_id 店铺分类ID列表
     * @apiParam {Object[]} goods_body  商品详情
     * @apiParam {String} goods_body.mb_body.type  商品详情类型（image图片text文字）
     * @apiParam {String} goods_body.mb_body.value  商品详情值
     * @apiParam {String} result.goods.mb_body.value_url  商品详情图片链接
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function save_goods() {
        $this->checkStore();
        $common_id = intval(input('param.goods_id'));
        $if_add = $common_id ? false : true;
        $gc_id = intval(input('post.class_id'));

        // 验证商品分类是否存在且商品分类是否为最后一级
        $data = model('goodsclass')->getGoodsclassForCacheModel();
        if (!isset($data[$gc_id]) || isset($data[$gc_id]['child']) || isset($data[$gc_id]['childchild'])) {
            ds_json_encode(10001, lang('store_goods_index_again_choose_category1'));
        }

            //商品分类 提供批量显示所有分类插件
            $storebindclass_model = model('storebindclass');
            $goods_class = model('goodsclass')->getGoodsclassForCacheModel();
            $condition = array();
            $condition[] = array('store_id', '=', $this->store_info['store_id']);
            $class_2 = isset($goods_class[$gc_id]['gc_parent_id']) ? $goods_class[$gc_id]['gc_parent_id'] : 0;
            $class_1 = isset($goods_class[$class_2]['gc_parent_id']) ? $goods_class[$class_2]['gc_parent_id'] : 0;
            $condition_class_1 = array(array('class_1', '=', ($class_1 > 0) ? $class_1 : (($class_2 > 0) ? $class_2 : $gc_id)));
            $condition_class_2 = array(array('class_2', '=', ($class_1 > 0) ? $class_2 : (($class_2 > 0) ? $gc_id : 0)));
            $condition_class_3 = array(array('class_3', '=', ($class_1 > 0 && $class_2 > 0) ? $gc_id : 0));
            $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
            if (empty($bind_info)) {
                $condition_class_3 = array(array('class_3', '=', 0));
                $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                if (empty($bind_info)) {
                    $condition_class_2 = array(array('class_2', '=', 0));
                    $condition_class_3 = array(array('class_3', '=', 0));
                    $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                    if (empty($bind_info)) {
                        $condition_class_1 = array(array('class_1', '=', 0));
                        $condition_class_2 = array(array('class_2', '=', 0));
                        $condition_class_3 = array(array('class_3', '=', 0));
                        $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                        if (empty($bind_info)) {
                            ds_json_encode(10001, lang('store_goods_index_again_choose_category2'));
                        }
                    }
                }
            }
        // 分类信息
        $goods_class = model('goodsclass')->getGoodsclassLineForTag(intval($gc_id));
        $goods_model = model('goods');

        $update_common = array();
        $update_common['goods_name'] = input('post.goods.goods_name');
        $update_common['goods_advword'] = input('post.goods.goods_advword');
        $update_common['gc_id'] = $gc_id;
        $update_common['gc_id_1'] = isset($goods_class['gc_id_1']) ? intval($goods_class['gc_id_1']) : 0;
        $update_common['gc_id_2'] = isset($goods_class['gc_id_2']) ? intval($goods_class['gc_id_2']) : 0;
        $update_common['gc_id_3'] = isset($goods_class['gc_id_3']) ? intval($goods_class['gc_id_3']) : 0;
        $update_common['gc_name'] = $goods_class['gctag_name'];
        $update_common['goods_image'] = input('post.goods.goods_image');
        $update_common['goods_price'] = floatval(input('post.goods.goods_price'));
        $update_common['goods_serial'] = input('post.goods.goods_serial', '');
        // 序列化保存手机端商品描述数据
        $mobile_body = serialize(input('post.goods_body/a'));

        $update_common['mobile_body'] = $mobile_body;
        $update_common['goods_commend'] = intval(input('post.goods.goods_commend'));
        $update_common['goods_state'] = ($this->store_info['store_state'] != 1) ? 0 : intval(input('post.goods.goods_state'));            // 店铺关闭时，商品下架
        $update_common['goods_verify'] = (config('ds_config.goods_verify') == 1) ? 10 : 1;
        $update_common['goods_vat'] = intval(input('post.goods.goods_vat'));



        //查询店铺商品分类
        $goods_stcids_arr = array();
        $sgcate_id_array = input('post.sgcate_id/a'); #获取数组
        if (!empty($sgcate_id_array)) {
            $sgcate_id_arr = array();
            foreach ($sgcate_id_array as $k => $v) {
                if ($v) {
                    $sgcate_id_arr[] = intval($v);
                }
            }
            if (!empty($sgcate_id_arr)) {
                $sgcate_id_arr = array_unique($sgcate_id_arr);
                $condition = array();
                $condition[] = array('store_id', '=', $this->store_info['store_id']);
                $condition[] = array('storegc_state', '=', '1');
                $condition[] = array('storegc_id', 'in', $sgcate_id_arr);
                $store_goods_class = model('storegoodsclass')->getStoregoodsclassList($condition);
                if (!empty($store_goods_class)) {
                    foreach ($store_goods_class as $k => $v) {
                        if ($v['storegc_id'] > 0) {
                            $goods_stcids_arr[] = $v['storegc_id'];
                        }
                        if ($v['storegc_parent_id'] > 0) {
                            $goods_stcids_arr[] = $v['storegc_parent_id'];
                        }
                    }
                    $goods_stcids_arr = array_unique($goods_stcids_arr);
                    sort($goods_stcids_arr);
                }
            }
        }
        if (empty($goods_stcids_arr)) {
            $update_common['goods_stcids'] = '';
        } else {
            $update_common['goods_stcids'] = ',' . implode(',', $goods_stcids_arr) . ',';
        }

        if (!$if_add) {//编辑
            $sellergoodsonline_validate = ds_validate('sellergoodsonline');
            if (!$sellergoodsonline_validate->scene('edit_save_goods')->check($update_common)) {
                ds_json_encode('10001', $sellergoodsonline_validate->getError());
            }
            $return = $goods_model->editGoods($update_common, array('goods_id' => $common_id, 'store_id' => $this->store_info['store_id']));
        } else {

            // 保存数据
            $update_common['store_id'] = $this->store_info['store_id'];
            $update_common['store_name'] = $this->store_info['store_name'];
            $update_common['goods_addtime'] = TIMESTAMP;
            $update_common['goods_type'] = input('post.goods.goods_type', 0);
            $goods_validate = ds_validate('sellergoodsadd');
            if (!$goods_validate->scene('save_goods')->check($update_common)) {
                ds_json_encode(10001, $goods_validate->getError());
            }
            $common_id = $goods_model->addGoods($update_common);
            if (!$common_id) {
                ds_json_encode(10001, lang('store_goods_index_goods_add_fail'));
            }
        }


        ds_json_encode(10000, lang('ds_common_op_succ'), array('goods_id' => $common_id));
    }

    /**
     * @api {POST} api/Sellergoods/goods_class 获取经营分类
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.bind_all 是否绑定全部分类（0否1是）
     * @apiSuccess {Object[]} result.class_list  商品分类列表
     * @apiSuccess {Int} result.class_list.id  分类ID
     * @apiSuccess {String} result.class_list.value  分类名称
     * @apiSuccess {Object[]} result.class_list.children  子分类列表
     * 
     */
    public function goods_class() {
        $bind_all = false;
        $store_bind_class_list = array();
        if ($this->store_info['bind_all_gc']) {
            $bind_all = true;
        } else {
            $storebindclass_model = model('storebindclass');
            $condition = array();
            $condition[] = array('class_1&class_2&class_3', '=', 0);
            $condition[] = array('store_id', '=', $this->store_info['store_id']);
            $condition[] = array('storebindclass_state', 'in', array(1, 2));
            if ($storebindclass_model->getStorebindclassInfo($condition)) {
                $bind_all = true;
            } else {
                $condition = array();
                $condition[] = array('store_id', '=', $this->store_info['store_id']);
                $condition[] = array('storebindclass_state', 'in', array(1, 2));
                $temp = $storebindclass_model->getStorebindclassList($condition, null);
                $class_1_ids = array();
                $class_2_ids = array();
                $class_3_ids = array();
                foreach ($temp as $class_info) {
                    if ($class_info['class_3'] == 0) {
                        if ($class_info['class_2'] == 0) {
                            $class_1_ids[] = $class_info['class_1'];
                        } else {
                            $class_2_ids[] = $class_info['class_2'];
                        }
                    } else {
                        $class_3_ids[] = $class_info['class_3'];
                    }
                }
                $goodsclass_list = array();
                if (!empty($class_1_ids)) {
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_1_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                    $temp_2 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $class_1_ids)))->column('gc_id');
                    if (!empty($temp_2)) {
                        $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_2)));
                        $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                        $temp_3 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $temp_2)))->column('gc_id');
                        if (!empty($temp_3)) {
                            $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_3)));
                            $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                        }
                    }
                }
                if (!empty($class_2_ids)) {
                    $temp_1 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $class_2_ids)))->column('gc_parent_id');
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_1)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                    $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_2_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                    $temp_3 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $class_2_ids)))->column('gc_id');
                    if (!empty($temp_3)) {
                        $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_3)));
                        $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                    }
                }
                if (!empty($class_3_ids)) {
                    $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_3_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                    $temp_2 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $class_3_ids)))->column('gc_parent_id');
                    $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_2)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                    $temp_1 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $temp_2)))->column('gc_parent_id');
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_1)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                }
                if (!empty($goodsclass_list)) {
                    $tree = new \mall\Tree();
                    $tree->setTree($goodsclass_list, 'gc_id', 'gc_parent_id', 'gc_name');
                    $result['class_list'] = $tree->getArrayList();
                    foreach ($result['class_list'] as $k1 => $v1) {
                        foreach ($v1['children'] as $k2 => $v2) {
                            foreach ($v2['children'] as $k3 => $v3) {
                                $result['class_list'][$k1]['children'][$k2]['children'][$k3]['image'] = goodsclass_image($v3['id']);
                            }
                        }
                    }
                    $store_bind_class_list = $result['class_list'];
                }
            }
        }

        ds_json_encode(10000, '', array('goods_class' => $store_bind_class_list, 'bind_all' => $bind_all));
    }

    /**
     * 课程列表
     */
    public function courses_list() {
        $goods_id = intval(input('param.goods_id'));
        if ($goods_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $goods = $goods_model->getGoodsInfoByID($goods_id);
        if ($goods['store_id'] != $this->store_info['store_id'] || $goods['goods_lock'] == 1) {
            ds_json_encode(10001, lang('param_error'));
        }

        //获取此商品的课程列表
        $goodscourses_model = model('goodscourses');
        $videoupload_model = model('videoupload');
        $condition = array();
        $condition[] = array('goods_id', '=', $goods_id);
        $goodscourses_list = $goodscourses_model->getGoodscoursesList($condition);
        foreach ($goodscourses_list as $key => $val) {
            $goodscourses_list[$key]['goodscourses_url'] = '';
            if($val['goodscourses_type']==0){
                $videoupload_info = $videoupload_model->getOneVideoupload(array(array('videoupload_id', '=', $val['goodscourses_type_id'])));
                if ($videoupload_info) {
                    $url = $videoupload_model->getVideoExpire($videoupload_info);
                    if ($url) {
                        $goodscourses_list[$key]['goodscourses_url'] = $url;
                    }
                }
            }
        }
        ds_json_encode(10000, '', array('goodscourses_list' => $goodscourses_list));
    }

    /**
     * 添加课程
     */
    function save_courses() {
        $goodscourses_id = intval(input('param.goodscourses_id'));
        //判断当前ID 是否属于机构
        $goods_id = intval(input('param.goods_id'));
        if ($goods_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $goods = $goods_model->getGoodsInfoByID($goods_id);
        if ($goods['store_id'] != $this->store_info['store_id'] || $goods['goods_lock'] == 1) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodscourses_type = input('post.goodscourses_type', 0);
        $videoupload_id = input('post.videoupload_id', 0);
        $live_apply_id = input('post.live_apply_id', 0);
        $minipro_live_id = input('post.minipro_live_id', 0);
        if ($live_apply_id) {
            $live_apply_model = model('live_apply');
            $condition = array();
            $condition[] = array('live_apply_state', '=', 1);
            $condition[] = array('live_apply_id', '=', $live_apply_id);

            $live_apply = $live_apply_model->getLiveApplyInfo($condition);
            if (empty($live_apply)) {
                ds_json_encode(10001, '直播不存在');
            }
        }
        $goodscourses_name = input('post.goodscourses_name');
        if (empty($goodscourses_name)) {
            ds_json_encode(10001, '课程标题不能为空');
        }
        $pand_id = input('post.pand_id/a');
        //录入
        $data = array(
            'goodscourses_free' => intval(input('post.goodscourses_free')),
            'goodscourses_exper' => intval(input('post.goodscourses_exper')),
            'goodscourses_name' => $goodscourses_name,
            'goodscourses_sort' => input('post.goodscourses_sort', 255),
            'goodscourses_type' => $goodscourses_type,
            'goodscourses_type_id' => $goodscourses_type==1?$live_apply_id:($goodscourses_type==2?$minipro_live_id:$videoupload_id),
            'goodscourses_class_id' => intval(input('post.goodscourses_class_id')),
            'goodscourses_class_name' => input('post.goodscourses_class_name',''),
            'baidu_pan_fsids' => !empty($pand_id)?json_encode($pand_id):'',
        );
        $goodscourses_model = model('goodscourses');
        if ($goodscourses_id) {
            $condition = array();
            $condition[] = array('goods_id', '=', $goods_id);
            $condition[] = array('store_id', '=', $this->store_info['store_id']);
            $condition[] = array('goodscourses_id', '=', $goodscourses_id);
            $result = $goodscourses_model->editGoodscourses($condition, $data);
        } else {
            $data['goods_id'] = input('param.goods_id');
            $data['store_id'] = $this->store_info['store_id'];
            $result = $goodscourses_model->addGoodscourses($data);
        }
        if ($result) {
            ds_json_encode(10000, lang('ds_common_op_succ'));
        }
    }

    /**
     * 编辑课程
     */
    function edit_courses() {
        $goods_id = intval(input('param.goods_id'));
        $goodscourses_id = intval(input('param.goodscourses_id'));
        $condition = array();
        $condition[] = array('goods_id', '=', $goods_id);
        $condition[] = array('store_id', '=', $this->store_info['store_id']);
        $condition[] = array('goodscourses_id', '=', $goodscourses_id);
        $goodscourses_model = model('goodscourses');
        $goodscourses = $goodscourses_model->getOneGoodscourses($condition);
        if (empty($goodscourses)) {
            ds_json_encode(10001, lang('param_error'));
        }
            $goodscourses['goodscourses_url']='';
            if($goodscourses['goodscourses_type']==0){
                $videoupload_model=model('videoupload');
                $videoupload_info=$videoupload_model->getOneVideoupload(array(array('videoupload_id', '=', $goodscourses['goodscourses_type_id'])));
                if($videoupload_info){
                    $url = $videoupload_model->getVideoExpire($videoupload_info);
                    $goodscourses['goodscourses_url']=$url;
                }
            }
        $goodscourses['baidu_pan_fsids'] = json_decode($goodscourses['baidu_pan_fsids'], true);
        ds_json_encode(10000, '', array('goodscourses' => $goodscourses));
    }

    /**
     * 删除课程
     */
    function del_courses() {
        $goodscourses_id = intval(input('param.goodscourses_id'));
        $condition = array();
        $condition[] = array('store_id', '=', $this->store_info['store_id']);
        $condition[] = array('goodscourses_id', '=', $goodscourses_id);
        $goodscourses_model = model('goodscourses');
        $result = $goodscourses_model->delGoodscourses($condition);
        if ($result) {
            ds_json_encode(10000, '删除成功');
        } else {
            ds_json_encode(10001, '参数错误');
        }
    }

    /*
     * 课程目录
     */

    function course_class_list() {
        $goods_id = intval(input('param.goods_id'));
        if (!$goods_id) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodscourses_class_model = model('goodscourses_class');
        $goodscourses_class_list = $goodscourses_class_model->getGoodscoursesClassList(array(array('goods_id', '=', $goods_id), array('store_id', '=', $this->store_info['store_id'])));
        ds_json_encode(10000, lang('ds_common_op_succ'), array('goodscourses_class_list' => $goodscourses_class_list));
    }

    /*
     * 新增课程目录
     */

    function course_class_add() {
        $goodscourses_class_model = model('goodscourses_class');
        $goodscourses_class_name = input('param.goodscourses_class_name');
        $goods_id = intval(input('param.goods_id'));
        if (!$goods_id || !$goodscourses_class_name) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodscourses_class_id = $goodscourses_class_model->addGoodscoursesClass(array(
            'goodscourses_class_name' => $goodscourses_class_name,
            'goods_id' => $goods_id,
            'store_id' => $this->store_info['store_id'],
        ));
        ds_json_encode(10000, lang('ds_common_op_succ'), array('goodscourses_class_id' => $goodscourses_class_id));
    }

    /*
     * 删除课程目录
     */

    function course_class_del() {
        $goodscourses_class_id = intval(input('param.goodscourses_class_id'));
        if (!$goodscourses_class_id) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodscourses_class_model = model('goodscourses_class');
        $goodscourses_class_model->delGoodscoursesClass(array(array('goodscourses_class_id', '=', $goodscourses_class_id), array('store_id', '=', $this->store_info['store_id'])));
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

    /*
     * 排序课程目录
     */

    function course_class_sort() {
        $sort = input('param.goodscourses_class_list/a');
        if (!$sort) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goodscourses_class_model = model('goodscourses_class');
        foreach ($sort as $val) {
            if (!$val['goodscourses_class_sort'] || !$val['goodscourses_class_id']) {
                ds_json_encode(10001, lang('param_error'));
            }
            $goodscourses_class_model->editGoodscoursesClass(array('goodscourses_class_sort' => $val['goodscourses_class_sort']), array(array('goodscourses_class_id', '=', $val['goodscourses_class_id'])));
        }
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

}
